﻿using Client;
using Shared.Model;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace ManageSystem.Dialog
{
    public partial class DialogNodeUpdate : Form
    {
        private FLOW _selectedFlow = null;
        private List<NODE> _listNodeNomal = null;
        private List<NODE> _listNodeOther = null;
        public DialogNodeUpdate(FLOW flow)
        {
            _selectedFlow = flow;
            InitializeComponent();
        }
        //清空工序描述和工序名称
        private void ClearText()
        {
            this.textBoxNodeName.Clear();
            this.textBoxNodeContext.Clear();
        }
        //清空工序信息表
        private void ClearListView()
        {
            this.listViewNodeOther.Items.Clear();
            this.listViewNodeNormal.Items.Clear();
        }

        //添加工序信息到ListView
        private void AddListView(ListView view, NODE node)
        {
            if (view == null || node == null)
            {
                MessageBox.Show("传入数据为空，不能添加到ListView中");
                return;
            }

            ListViewItem item = new ListViewItem();
            item.Text = node.ID.ToString();
            item.SubItems.Add(node.NAME);
            item.SubItems.Add(node.CONTEXT);
            if (node.SORT != null)
                item.SubItems.Add(node.SORT.ToString());
            else
                item.SubItems.Add("");

            if (node.LAST_ID != null)
                item.SubItems.Add(node.LAST_ID.ToString());
            else
                item.SubItems.Add("");

            if (node.NEXT_ID != null)
                item.SubItems.Add(node.NEXT_ID.ToString());
            else
                item.SubItems.Add("");

            if (node.ERROR_ID != null)
                item.SubItems.Add(node.ERROR_ID.ToString());
            else
                item.SubItems.Add("");

            view.Items.Add(item);
        }

        //加载信息
        private void DialogNodeUpdate_Load(object sender, EventArgs e)
        {

            ClearListView();
            ClearText();

            if (_selectedFlow != null)
            {
                this.textFlowId.Text = _selectedFlow.ID.ToString();
                this.textFlowName.Text = _selectedFlow.NAME;
                this.richTextBoxFlowContext.Text = _selectedFlow.CONTEXT;
                if (_selectedFlow.NODE_START != null)
                    this.textFlowNodeStart.Text = _selectedFlow.NODE_START.ToString();
                if (_selectedFlow.NODE_END != null)
                    this.textFlowNodeEnd.Text = _selectedFlow.NODE_END.ToString();
                this.richTextBoxNodeAll.Text = _selectedFlow.NODE_ALL;
            }

            //加载正常的工序信息
            NODE nodeW = new NODE();
            nodeW.SetWhere();
            nodeW.FLOW_ID = _selectedFlow.ID;
            nodeW.FLAG = true;
            var selectNodeNomal = MethodWcf.SelectNodeClient(nodeW);
            if (selectNodeNomal.result)
            {
                _listNodeNomal = (from n in selectNodeNomal.value
                                  orderby n.SORT
                                  select n).ToList();

                for (int i = 0; i < _listNodeNomal.Count; i++)
                {
                    AddListView(listViewNodeNormal, _listNodeNomal[i]);
                }
            }
            //加载额外的工序信息
            nodeW.SetWhere();
            nodeW.FLAG = false;
            var selectNodeOther = MethodWcf.SelectNodeClient(nodeW);
            if (selectNodeOther.result)
            {
                _listNodeOther = selectNodeOther.value;
                for (int j = 0; j < _listNodeOther.Count; j++)
                {
                    AddListView(listViewNodeOther, _listNodeOther[j]);
                }
            }

        }

        //保存工序信息和流程信息
        private void btnSave_Click(object sender, EventArgs e)
        {
            string flowName = this.textFlowName.Text.Trim();//流程名称
            string flowContext = this.richTextBoxFlowContext.Text.Trim();//流程描述

            _selectedFlow.Clear();
            _selectedFlow.SetWhere();
            _selectedFlow.ID = _selectedFlow.ID;

            _selectedFlow.SetUpdate();
            if (!string.IsNullOrEmpty(flowName))
                this._selectedFlow.NAME = flowName;
            if (!string.IsNullOrEmpty(flowContext))
                this._selectedFlow.CONTEXT = flowContext;

            if (this.listViewNodeNormal.Items.Count == 0)//没有节点
            {
                _selectedFlow.NODE_START = 0;
                _selectedFlow.NODE_END = 0;
                _selectedFlow.NODE_ALL = null;

                var update = MethodWcf.UpdateFlowClient(_selectedFlow);
                if (update.result)
                {
                    MessageBox.Show("保存成功");
                }
                else
                {
                    MessageBox.Show(update.message);
                }
                Close();
            }

            _selectedFlow.NODE_START = _listNodeNomal[0].ID;
            _selectedFlow.NODE_END = _listNodeNomal[_listNodeNomal.Count - 1].ID;

            string nodeAll = null;
            for (int i = 0; i < _listNodeNomal.Count; i++)
            {
                NODE before = null;
                NODE node = null;
                NODE after = null;

                if (i != 0)
                {
                    before = _listNodeNomal[i - 1];
                }
                if (i != _listNodeNomal.Count - 1)
                {
                    after = _listNodeNomal[i + 1];
                }
                node = _listNodeNomal[i];

                node.SetWhere();//更新条件
                node.ID = node.ID;
                node.SetUpdate();//更新内容

                if (before != null)
                {
                    node.LAST_ID = before.ID;
                }
                else//开始工序
                {
                    node.LAST_ID = 0;
                }

                if (after != null)
                {
                    node.NEXT_ID = after.ID;
                }
                else//结束工序
                {
                    node.NEXT_ID = 0;
                }

                if (!string.IsNullOrEmpty(flowName))
                {
                    node.FLOW_NAME = flowName;
                }

                nodeAll += node.ID + ",";

                //更新相应的NODE
                var updateNode = MethodWcf.UpdateNodeClient(node);
                if (!updateNode.result)
                {
                    MessageBox.Show(updateNode.message);
                }
            }

            //更新流程
            _selectedFlow.NODE_ALL = nodeAll.TrimEnd(',');
            var updateFlow = MethodWcf.UpdateFlowClient(_selectedFlow);
            if (!updateFlow.result)
            {
                MessageBox.Show(updateFlow.message);
            }

            this.Close();
        }
        //添加工序
        private void AddNode(bool IsNormal = true)
        {
            string name = this.textBoxNodeName.Text;
            string context = this.textBoxNodeContext.Text;

            if (string.IsNullOrEmpty(name) || string.IsNullOrEmpty(context))
            {
                MessageBox.Show("工序名称和描述不能为空", "警告", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }

            try
            {
                int sort = 1;//没有工序时，排序为1
                if (_listNodeNomal != null && _listNodeNomal.Count >= 1)
                {
                    sort = (from n in _listNodeNomal
                            select n.SORT.Value).Max() + 1;
                }

                var node = new NODE();
                node.SetUpdate();
                node.NAME = name;
                node.FLOW_ID = _selectedFlow.ID;
                node.FLOW_NAME = _selectedFlow.NAME;
                if (IsNormal)//正常工序有排序
                    node.SORT = sort;
                node.CONTEXT = context;
                node.FLAG = IsNormal;

                var insertNode = MethodWcf.InsertNodeClient(node);
                if (insertNode.result)
                {
                    MessageBox.Show("添加成功");
                }
                else
                {
                    MessageBox.Show("添加失败");
                }
            }
            catch
            {
                MessageBox.Show("增加工序失败");
            }
            finally
            {
                ClearText();//清空
                DialogNodeUpdate_Load(null, null);//重新加载数据
            }
        }

        //添加到最后
        private void buttonAdd_Click(object sender, EventArgs e)
        {
            AddNode();
        }


        //增加附加工序
        private void buttonAddFX_Click(object sender, EventArgs e)
        {
            AddNode(false);
        }

        private void DeleteNode(bool isNormal = true)
        {
            if (isNormal &&
                (this._listNodeNomal.Count == 0 
                || this.listViewNodeNormal.SelectedItems.Count == 0)) return;

            if (isNormal == false &&
                (this._listNodeOther.Count == 0 
                ||this.listViewNodeOther.SelectedItems.Count==0)) return;

            //弹出一个对话框，判断是否删除
            DialogResult ret = MessageBox.Show("删除后不可还原，与之关联的信息将清空\n是否删除？", "警告", MessageBoxButtons.YesNo, MessageBoxIcon.Warning);
            if (ret == DialogResult.No) return;

            long nodeId = 0;
            if (isNormal)
            {
                var selected = this.listViewNodeNormal.SelectedItems[0].Text;
                if (long.TryParse(selected, out nodeId) == false)
                {
                    MessageBox.Show("获取工序号码失败");
                    return;
                }
            }
            else
            {
                var selected = this.listViewNodeOther.SelectedItems[0].Text;
                if (long.TryParse(selected, out nodeId) == false)
                {
                    MessageBox.Show("获取工序号码失败");
                    return;
                }
            }

            //将于此关联的所有数据设置为空
            NODE nodeWhere = new NODE();
            nodeWhere.SetWhere();
            nodeWhere.NEXT_ID = nodeId;
            //将所有的nextId设置为空
            var nextList = MethodWcf.SelectNodeClient(nodeWhere);
            if (nextList.result)
            {
               for(int i = 0; i < nextList.value.Count; i++)
                {
                    var temp = nextList.value[i];
                    temp.SetWhere();
                    temp.ID = temp.ID;
                    temp.SetUpdate();
                    temp.NEXT_ID = null;
                    MethodWcf.UpdateNodeClient(temp);
                }
            }

            //将所有lastID设置为空
            nodeWhere.Clear();
            nodeWhere.SetWhere();
            nodeWhere.LAST_ID = nodeId;

            var lastList = MethodWcf.SelectNodeClient(nodeWhere);
            if (lastList.result)
            {
                for (int i = 0; i < lastList.value.Count; i++)
                {
                    var temp = lastList.value[i];
                    temp.SetWhere();
                    temp.ID = temp.ID;
                    temp.SetUpdate();
                    temp.LAST_ID = null;
                    MethodWcf.UpdateNodeClient(temp);
                }
            }

            //将所有ERROR_ID设置为空
            nodeWhere.Clear();
            nodeWhere.SetWhere();
            nodeWhere.ERROR_ID = nodeId;

            var errorList = MethodWcf.SelectNodeClient(nodeWhere);
            if (errorList.result)
            {
                for (int i = 0; i < errorList.value.Count; i++)
                {
                    var temp = errorList.value[i];
                    temp.SetWhere();
                    temp.ID = temp.ID;
                    temp.SetUpdate();
                    temp.ERROR_ID = null;
                    MethodWcf.UpdateNodeClient(temp);
                }
            }


            //从数据库中删除相应的工序ID
            NODE nodeW = new NODE();
            nodeW.SetWhere();
            nodeW.ID = nodeId;

            var deleteNode = MethodWcf.DeleteNodeClient(nodeW);
            if (deleteNode.result)
            {
                MessageBox.Show("删除成功");
            }
            else
            {
                MessageBox.Show("删除失败");
            }

            ClearListView();
            ClearText();
            DialogNodeUpdate_Load(null, null);
        }

        //删除正常工序
        private void buttonDelete_Click(object sender, EventArgs e)
        {
            DeleteNode();
        }

        //删除附加工序
        private void buttonFXDel_Click(object sender, EventArgs e)
        {
            DeleteNode(false);
        }
        //刷新界面
        private void buttonRefush_Click(object sender, EventArgs e)
        {
            this.ClearText();
            this.ClearListView();
            this.DialogNodeUpdate_Load(null, null);
        }

        private void UpOrDown(bool isUp = true)
        {
            try
            {
                if (this._listNodeNomal.Count <= 1 || this.listViewNodeNormal.SelectedItems.Count==0) return;//如果list的行数小于等于1，移动没有价值
                var selected = this.listViewNodeNormal.SelectedItems[0];
                int selectedIndex = selected.Index;

                if (isUp && selectedIndex == 0)
                {
                    MessageBox.Show("选中了第一行，上移无效");
                    return;
                }

                if (isUp == false && selectedIndex == this.listViewNodeNormal.Items.Count - 1)
                {
                    MessageBox.Show("选中了最后一行，下移操作无效");
                    return;
                }

                long choiceId = long.Parse(selected.Text);
                long otherId = 0;
                if (isUp)
                    otherId = long.Parse(this.listViewNodeNormal.Items[selectedIndex - 1].Text);
                else
                    otherId = long.Parse(this.listViewNodeNormal.Items[selectedIndex + 1].Text);

                var choice = (from r in _listNodeNomal
                              where r.ID == choiceId
                              select r).FirstOrDefault();

                var other = (from r in _listNodeNomal
                             where r.ID == otherId
                             select r).FirstOrDefault();

                if (choice == null || other == null)
                {
                    MessageBox.Show("交换顺序失败");
                    return;
                }

                int sort = choice.SORT.Value;
                choice.Clear();
                choice.SetWhere();
                choice.ID = choice.ID;

                choice.SetUpdate();
                choice.SORT = other.SORT;
                var updateChoice = MethodWcf.UpdateNodeClient(choice);

                other.Clear();
                other.SetWhere();
                other.ID = other.ID;
                other.SetUpdate();
                other.SORT = sort;
                var updateOther = MethodWcf.UpdateNodeClient(other);


                if (updateChoice.result == false || updateOther.result == false)
                {
                    MessageBox.Show("更新失败");
                }
                else
                {
                    MessageBox.Show("更新成功");
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
            finally
            {
                buttonRefush_Click(null, null);
            }
        }
        //工序上移
        private void buttonUp_Click(object sender, EventArgs e)
        {
            UpOrDown();
        }
        //工序下移
        private void buttonDown_Click(object sender, EventArgs e)
        {
            UpOrDown(false);
        }
        //关闭时保存
        private void DialogNodeUpdate_FormClosed(object sender, FormClosedEventArgs e)
        {
            btnSave_Click(null, null);
        }
    }
}
